//
//  HMWorkSelectCourseVC.m
//  优学荟管理系统
//
//  Created by 陈辉明 on 2017/12/25.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HMWorkSelectCourseVC.h"
#import "HMWorkSelectCourseCell.h"
#import "HMWorkSelectCourseModel.h"
#import "HMWorkSelectStudentVC.h"

@interface HMWorkSelectCourseVC ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITextField *searchTextField;
@property(nonatomic,strong) NSMutableArray *dataSource;
@property (strong, nonatomic) NSIndexPath *selIndex;//单选，当前选中的行
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,assign) BOOL isTrue;
@property (nonatomic,assign) NSInteger page;

@end

@implementation HMWorkSelectCourseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.searchTextField.delegate = self;
    self.searchTextField.returnKeyType= UIReturnKeySearch;
    [self setUpTableView];
    [self setUpRefresh];
    self.title = @"选择课程";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(leftBarButtonItemAction) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}]; //设置标题颜色
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色

    [SVProgressHUD dismiss];
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];//设置标题颜色
}

- (void)leftBarButtonItemAction{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)setUpTableView {
    self.tableView.contentInset = UIEdgeInsetsMake(-54, 0, 0, 0);
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 60;
    [self.tableView registerNib:[UINib nibWithNibName:@"HMWorkSelectCourseCell" bundle:nil] forCellReuseIdentifier:@"HMWorkSelectCourseCellId"];
    
    
}

#pragma mark --- 上拉加载和下拉刷新方法的实现
- (void)setUpRefresh{
    
    //下拉刷新
    self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    //自动更改透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    //结束头部刷新
    [self.tableView.mj_header endRefreshing];
    //结束尾部刷新
    [self.tableView.mj_footer endRefreshing];
    
    
}

/**
 *  上拉加载
 */
- (void)upRefresh{
    
    self.isTrue = NO;
    self.page++;
    [self setNetWork];
    
}
/**
 *  下拉刷新
 */

- (void)downRefresh{
    self.isTrue = YES;
    self.page = 1;
    [self setNetWork];
    
    
}


#pragma mark - 数据源
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HMWorkSelectCourseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HMWorkSelectCourseCellId" forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.row];
    
    //当上下拉动的时候，因为cell的复用性，我们需要重新判断一下哪一行是打勾的
    if (_selIndex == indexPath) {
        //        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        cell.selectButton.selected = YES;
    }else {
        //        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectButton.selected = NO;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //若选择的课程的大类目为文化课，点击确定后则弹框
    
    
    
    
    
    //之前选中的，取消选择
    HMWorkSelectCourseCell *celled = [tableView cellForRowAtIndexPath:_selIndex];
    celled.selectButton.selected = NO;
    //记录当前选中的位置索引
    _selIndex = indexPath;
    //当前选择的打勾
    HMWorkSelectCourseCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selectButton.selected = YES;
   
}

#pragma mark - 网络请求
- (void)setNetWork {
    
    NSString *url;
    
    if (self.isTeacher) {
        if (self.searchTextField.text.length != 0 &&self.searchTextField.text) {
            
            url = [NSString stringWithFormat:@"trainLesson.do?action=getTrainLessonForRecord2&pageNumber=%ld&searchName=%@",self.page,self.searchTextField.text];
            url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        } else {
            
            url = [NSString stringWithFormat:@"trainLesson.do?action=getTrainLessonForRecord2&pageNumber=%ld&searchName=%@",self.page,@""];
            url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        }
        NSLog(@"%@ %@",LLBaseURLTeacher(url),[AccountTool shareAccountTool].currentAccount.authCode);
        [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
        [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
        [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
        [SVProgressHUD showWithStatus:LLLoading];
        
        [NetManager Get:LLBaseURLTeacher(url) Auth:YES Params:nil Success:^(id Obj) {
            
            if ([[Obj valueForKey:@"code"]integerValue] == 1000) {
                [SVProgressHUD dismiss];
                if (self.isTrue == YES) {
                    [self.dataSource removeAllObjects];
                    self.selIndex = nil;
                }
                
                for (NSDictionary *dict in Obj[@"t"][@"dataList"]) {
                    
                    HMWorkSelectCourseModel *model = [HMWorkSelectCourseModel HMWorkSelectCourseModelWithDict:dict];
                    [self.dataSource addObject:model];
                }
                
                [self.tableView reloadData];
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
                
            }
            
            else {
                [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
            }
        } Fail:^(NSError *Error) {
            [SVProgressHUD showErrorWithStatus:NetErr];
            
        }];
        
        
    }else {
        if (self.searchTextField.text.length != 0 &&self.searchTextField.text) {
            
            url = [NSString stringWithFormat:@"yxhUser.do?action=getLessonList&pageNumber=%ld&oid=%@&searchName=%@",self.page,[AccountTool shareAccountTool].currentAccount.oid,self.searchTextField.text];
            url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        } else {
            
            url = [NSString stringWithFormat:@"yxhUser.do?action=getLessonList&pageNumber=%ld&oid=%@&searchName=%@",self.page,[AccountTool shareAccountTool].currentAccount.oid,@""];
            url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        }
        
        NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
        [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
        [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
        [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
        [SVProgressHUD showWithStatus:LLLoading];
        
        [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
            
            if ([[Obj valueForKey:@"code"]integerValue] == 1000) {
                [SVProgressHUD dismiss];
                if (self.isTrue == YES) {
                    [self.dataSource removeAllObjects];
                    self.selIndex = nil;
                }
                
                for (NSDictionary *dict in Obj[@"t"][@"dataList"]) {
                    
                    HMWorkSelectCourseModel *model = [HMWorkSelectCourseModel HMWorkSelectCourseModelWithDict:dict];
                    [self.dataSource addObject:model];
                }
                
                [self.tableView reloadData];
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
                
            }
            
            else {
                [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
            }
        } Fail:^(NSError *Error) {
            [SVProgressHUD showErrorWithStatus:NetErr];
            
        }];
        
        
    }
    
    
    
    
    
    

}




#pragma mark - 键盘搜索处理
-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    [self.searchTextField resignFirstResponder];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (self.searchTextField.text.length!=0) {
         [self.tableView.mj_header beginRefreshing];
        [self.searchTextField resignFirstResponder];
    }else{
        [MBProgressHUD showError:@"请输入搜索内容"];
    }
    
    return YES;
    
}


-(NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray new];
    }
    return _dataSource;
}

#pragma mark - 点击事件
- (IBAction)clickSureButton:(id)sender {
    
    if (_selIndex == nil) {
        [SVProgressHUD showErrorWithStatus:@"请选择课程"];
    } else {
        HMWorkSelectCourseModel *model = self.dataSource[self.selIndex.row];
        if([model.categoryName isEqualToString:@"文化类"])
        {
            
            dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
     message:@"是否选择使用题库布置作业?"preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault
            handler:^(UIAlertAction * action) {
                HMWorkSelectStudentVC *vc = [HMWorkSelectStudentVC new];
                vc.lessionId = model.Id;
                vc.isCategory=YES;
                [self.navigationController pushViewController:vc animated:YES];
            }];
                UIAlertAction* defaultAction1 = [UIAlertAction actionWithTitle:@"我要出题" style:UIAlertActionStyleDefault
                    handler:^(UIAlertAction * action) {
                        HMWorkSelectStudentVC *vc = [HMWorkSelectStudentVC new];
                        vc.lessionId = model.Id;
                        [self.navigationController pushViewController:vc animated:YES];
                                                                      }];
                [alert addAction:defaultAction1];
                [alert addAction:defaultAction];
             
                [self presentViewController:alert animated:YES completion:nil];
                
                        });
        }
        else
        {
            HMWorkSelectStudentVC *vc = [HMWorkSelectStudentVC new];
            vc.lessionId = model.Id;
            [self.navigationController pushViewController:vc animated:YES];
        }
       
    }
    
    
//    if (self.selectRowBlock && _selIndex != nil) {
//        self.selectRowBlock(self.dataSource[self.selIndex.row]);
//    }
//
    
}




@end
